package edu.sias.userQuestion.utils;


import com.fasterxml.jackson.databind.ObjectMapper;
import edu.sias.question.constants.QuestionConstants;
import edu.sias.question.domain.dto.QuestionDTO;
import edu.sias.question.utils.EsRespons;
import edu.sias.userQuestion.domain.Submit;
import edu.sias.userQuestion.domain.Userques;
import org.apache.http.HttpHost;
import org.elasticsearch.ElasticsearchException;
import org.elasticsearch.action.admin.indices.delete.DeleteIndexRequest;
import org.elasticsearch.action.delete.DeleteRequest;
import org.elasticsearch.action.get.GetRequest;
import org.elasticsearch.action.get.GetResponse;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.action.support.master.AcknowledgedResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestClient;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.client.indices.CreateIndexRequest;
import org.elasticsearch.common.xcontent.XContentType;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.util.Map;

/**
 * Elasticsearch 创建题库内容工具类（Spring 管理生命周期）
 */
@Component
public class Esuq {

    private RestHighLevelClient client;
    private static final ObjectMapper objectMapper = new ObjectMapper();
    /**
     * 初始化客户端（可配置化改造后应从配置读取 host）
     */

    private void init() {
        this.client = new RestHighLevelClient(
                RestClient.builder(HttpHost.create("http://127.0.0.1:9200"))
        );
    }
    /**
     *
     */
    public void createIndexMAPPING(String index) throws IOException {
        init();
        // 1. 创建Request对象
        CreateIndexRequest request = new CreateIndexRequest(index);

        // 2. 请求参数, MAPPING_TEMPLATE 是静态常量字符串, 内容是创建索引库的DSL语句
        request.source(QuestionConstants.MAPPING_TEMPLATE, XContentType.JSON);

        // 3. 发起请求
        client.indices().create(request, RequestOptions.DEFAULT);
        destroy();
    }
    /**
     * 插入文档到指定索引
     *
     * @param index 索引名称
     * @param id    文档ID
     * @param text  要插入的文本内容
     */
    /**
     * 插入文档到指定索引
     *
     * @param
     * @param
     * @param
     * @param
     */
    public void add(Submit submit) throws IOException {
        init();
        // 1. 创建Request对象

            IndexRequest request = new IndexRequest("userquestion")
                    .id(submit.getId())
                    .source(objectMapper.writeValueAsBytes(submit), XContentType.JSON);

            client.index(request, RequestOptions.DEFAULT);
        destroy();

    }

    /**
     * 根据ID查询文档
     *
     * @param
     * @param id    文档ID
     * @return 返回文档内容（JSON 字符串），如果不存在则返回 null
     */
    public Submit getById(String id) throws IOException {
        init();
        GetRequest request = new GetRequest("userquestion", id);
        GetResponse response = client.get(request, RequestOptions.DEFAULT);
        if (response.isExists()){
            Map<String, Object> sourceMap = response.getSourceAsMap();
        return EsRespons.SubmitMap(sourceMap);
        }

        destroy();

        return null;
    }

    /**
     * 根据 ID 删除文档
     *
     * @param
     * @param id    文档 ID
     * @return 是否删除成功
     */
    public void deleteById( String id) throws IOException {
        init();
        try {
            DeleteRequest request = new DeleteRequest("userquestion", id);
            client.delete(request, RequestOptions.DEFAULT);

        } catch (IOException e) {
            e.printStackTrace();
            throw e;
        } finally {
            destroy();
        }
    }
    //



    /**
     * 销毁客户端（释放资源）
     */

    private void destroy() {
        if (client != null) {
            try {
                client.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}
